<?php
namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemMenu;
use app\admin\model\SystemRole;
use think\facade\Log;
use think\App;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class Login extends BaseController
{
    public function login()
    {
        return View::fetch('login/login');
    }

    /**
     * 登录
     * @return $this
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function loginInfo(){
        $getData = Request::post();
        if(!$getData['account']) return $this->fail('账号不能为空');
        if(!$getData['password']) return $this->fail('密码不能为空');
        $systemAdminModel = new SystemAdmin();
        $adminInfo = $systemAdminModel->getAdminInfoByAccount($getData['account']);
        if (!$adminInfo) return $this->fail('请输入正确的账号或密码');
        if($adminInfo['status'] == 0 ) return $this->fail('当前账号已被冻结');
        //var_dump(password_hash($getData['password'], PASSWORD_BCRYPT));
        if (!password_verify((string)$getData['password'], $adminInfo['pwd'])){
            return $this->fail('账户或者密码错误');
        }
        //保存登录状态
        session('admin_id',$adminInfo->admin_id);
        session('account',$adminInfo->account);
        session('real_name',$adminInfo->real_name);
        session('admin_info',$adminInfo->toArray());
        $roleIdList = explode(",",$adminInfo['roles']);
        if(in_array(1,$roleIdList)){
            $getPowerId = ['role'=>'all'];
        }else{
            $systemRoleModel = new SystemRole();
            $powerIdList = $systemRoleModel->getRolePowerIdList($adminInfo['roles']);
            $getPowerId = ['role'=>'admin','roleIdList'=>$powerIdList];
        }
        cache('adminPowerIdList'.$adminInfo->admin_id,$getPowerId,155000);
        $saveData = [
            'last_time'=>date('Y-m-d H:i:s', time()),
            'last_ip'=>request()->ip(),
            'login_count'=>($adminInfo->login_count + 1),
        ];
        $userResult = $systemAdminModel->updateInfo($adminInfo->admin_id,$saveData);
        return $this->success('登录成功');
    }

    /**
     * 退出登录
     * @return string
     */
    function loginOut(){
        cache('menu_list',null);
        cache('adminPowerIdList'.session('admin_id'),null);
        session('admin_id',null);
        session('account',null);
        session('real_name',null);
        session('admin_info',null);
        return redirect('/admin/login/login');
    }
  

}


